package cn._51doit.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import java.time.Duration;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Properties;
/**
 * @create: 2021-10-12 20:29
 * @author: 珠穆朗玛峰顶峰的男人
 * @program: kafka_java_scala
 * 消费者只读取已经提交事务的数据
 **/
@SuppressWarnings("all")
public class JavaConsumerTransaction {
    public static void main(String[] args) {
        Properties properties = new Properties();
        // 连接kafka节点
        properties.setProperty("bootstrap.servers", "doit01:9092,doit02:9092,doit03:9092");
        //指定key反序列化方式
        properties.setProperty("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        //指定value反序列化方式
        properties.setProperty("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        //指定消费这组id
        properties.setProperty("group.id", "j01");
        //指定偏移量
        properties.setProperty("auto.offset.reset", "earliest");
        //指定不自动提交偏移量
        properties.setProperty("enable.auto.commit", "false");
        //读取已经提交事务的数据
        properties.setProperty("isolation.level", "read_committed");

        //消费者实例
        KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(properties);
        //指定topic 可以指定多个topic
        kafkaConsumer.subscribe(Arrays.asList("word"));
        while (true) {
            //读数据方法poll
            Iterator<ConsumerRecord<String, String>> it = kafkaConsumer.poll(Duration.ofSeconds(5)).iterator();
            while (it.hasNext()) {
                ConsumerRecord<String, String> consumerRecord = it.next();
                System.out.println(consumerRecord);
            }
        }
    }
}
